package sample;

import java.awt.Color;

import robocode.HitRobotEvent;
import robocode.HitWallEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;

public class RoboAR extends Robot {

	private double minDist = 100.0;
	private boolean wall = false;
	private boolean captured = false;
	@Override
	public void run() {
		setRadarColor(Color.GREEN);
		alinhar(getWidth()/2.0, getBattleFieldHeight()/2.0);
		int i = 1;
		while(true){
			if( !wall && !captured ) ahead(200);
			switch( i ){
				case 1:
					turnRadarRight(90.0);
					i++;
					break;
				case 2:
					turnRadarLeft(90.0);
					i++;
					break;
				case 3:
					turnRadarLeft(90.0);
					i++;
					break;
				case 4:
					turnRadarRight(90.0);
					i++;
					break;
			}
			if( i > 4 ) i = 1;
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onScannedRobot(ScannedRobotEvent event) {
		if( wall && !event.getName().equals("sample.RoboScannerA") && event.getDistance() < 80) {
			double dist = event.getDistance();
			turnRight(event.getBearing());
			if( !captured && dist < minDist ) minDist = dist;
			else{ 
				ahead(dist - getWidth());
				captured = true;
			}
		}
	}
	
	@Override
	public void onHitRobot(HitRobotEvent event) {
		double r = Math.random();
		if( r > 0.5 ){
			turnLeft(90.0);
			ahead(getWidth()*2.0);
			turnRight(90.0);
		}else{
			turnRight(90.0);
			ahead(getWidth()*2.0);
			turnLeft(90.0);
		}
		if( wall && !captured )
			alinhar(getX()+10, getY());
		else if( !captured )
			alinhar(getWidth()/2.0, getBattleFieldHeight()/2.0);
	}

	@Override
	public void onHitWall(HitWallEvent event) {
		alinhar(getX()+10, getY());
		wall = true;
	}

	private void alinhar(double targetX, double targetY){
		double co = targetY - getY();
		double ca = targetX - getX();
		double d = 0;
		if( co < 0 && ca < 0 )
			d = (90.0 - Math.toDegrees( Math.atan(co/ca) )) + 180.0;
		else if( ca < 0 )
			d = (90.0 + Math.abs(Math.toDegrees( Math.atan(co/ca) )) ) + 180.0;
		else if( co < 0 )
			d = 90.0 + Math.abs(Math.toDegrees( Math.atan(co/ca) ));
		else
			d = 90.0 - Math.toDegrees( Math.atan(co/ca) );
		double h = getHeading();
		turnRight(d-h);
	}
}
